﻿using Commons;
using JWT;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RMS
{
    public class TokenFilter : Attribute, IActionFilter
    {
        private ITokenHelper tokenHelper;
        private IRedisService redisService;
        private readonly ILogger<TokenFilter> _logger;

        public TokenFilter(ITokenHelper _tokenHelper, IRedisService redisService, ILogger<TokenFilter> _logger) //通过依赖注入得到数据访问层实例
        {
            this.tokenHelper = _tokenHelper;
            this.redisService = redisService;
            this._logger = _logger;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            ResultType result = new ResultType();
            //获取token
            //object tokenobj = context.ActionArguments["token"];//前端地址栏参数传参
            object tokenobj = context.HttpContext.Request.Headers["token"].ToString();//前端写在header里面获取的

            string token = tokenobj.ToString();
            string userId = "";
            //_logger.LogError("before"+token);
            TokenType tokenType = tokenHelper.ValiTokenState(token, a => a["iss"] == "WK" && a["aud"] == "EveryTestOne", action => { userId = action["userId"]; });
            // _logger.LogError("after:"+ tokenType + "-----"+ token);

            if (tokenType!=TokenType.Ok)
            {
                result.ResultCode = 401;
                result.ResultMsg = "token验证失败，请重新登录";
                context.Result = new JsonResult(result);
                return;
            }
            string tokenRedis = redisService.FindByKeyAsync<string>(userId).Result;
            if (!token.Equals(tokenRedis))
            {

                result.ResultCode = 401;
                result.ResultMsg = "token验证失败，请重新登录";
                context.Result = new JsonResult(result);
                return;
            }
            if (!string.IsNullOrEmpty(userId))
            {
                //给控制器传递参数(需要什么参数其实可以做成可以配置的，在过滤器里边加字段即可)
                //if(!context.ActionArguments.ContainsKey("userId"))
                context.ActionArguments.Add("userId", userId);

                //var controllername = context.RouteData.Values["controller"];
                //var actionname = context.RouteData.Values["action"];
                //string apiname = controllername + "/" + actionname;
                
                //if (!apiname.Equals("Sys/GetAllMenuByUser")&&redisService.FindByKeyAsync<List<string>>(userId+"_role")!=null&&!redisService.FindByKeyAsync<List<string>>(userId+"_role").Result.Contains(apiname))
                //{
                //    result.ResultCode = 403;
                //    context.Result = new JsonResult(result);
                //    return;
                //}
            }

            redisService.AddOrUpdateByKeyAsync(userId, redisService.FindByKeyAsync<string>(userId).Result,
                DateTime.Now.AddSeconds(600));
        }
    }
}
